/*
*获取ERP订单数据
 */
 package main

 import (
	 "net/http"
	 "encoding/json"
	 "strings"
	 "strconv"
	 "crypto/md5"
	 "encoding/hex"
	 "regexp"
	//  "reflect"
	 // "github.com/dgrijalva/jwt-go"
	 // "github.com/labstack/echo"
	 "io/ioutil"
	 "time"
	 "net/url"
 
	 "gopkg.in/mgo.v2/bson"
	 // "github.com/jinzhu/gorm"
	 "oxy_server/model"
	 "oxy_server/module/log"
	 "oxy_server/until"
 )
 
 type (
	salesdata struct {
		ID 									bson.ObjectId `json:"_id" bson:"_id"`
		OrderNumber 				string `json:"ordernumber" bson:"ordernumber"`
		OnlineOrderNumber 	string `json:"onlineordernumber" bson:"onlineordernumber"`
		PayDate 						int64 `json:"paydate" bson:"paydate"`
		ShipDate 						int64 `json:"shipdate" bson:"shipdate"`
		PackageNumber 			string `json:"packagenumber" bson:"packagenumber"`
		ShipUser 						string `json:"shipuser" bson:"shipuser"`
		City 								string `json:"city" bson:"city"`
		District 						string `json:"district" bson:"district"`
		Address 						string `json:"address" bson:"address"`
		LargeNumber 				string `json:"largenumber" bson:"largenumber"`
		Sku 								string `json:"sku" bson:"sku"`
		CargoName 					string `json:"cargoname" bson:"cargoname"`
		Size 								string `json:"size" bson:"size"`
		Color 							string `json:"color" bson:"color"`
		Count 							string `json:"count" bson:"count"`
		Price 							float64 `json:"price" bson:"price"`
		Amount 							float64 `json:"amount" bson:"amount"`
		Cost 								float64 `json:"cost" bson:"cost"`
	}
	insertsalesdata struct {
		OrderNumber 			string `json:"ordernumber" bson:"ordernumber"`
		OnlineOrderNumber	string `json:"onlineordernumber" bson:"onlineordernumber"`
		PayDate 					int64 `json:"paydate" bson:"paydate"`
		ShipDate 					int64 `json:"shipdate" bson:"shipdate"`
		PackageNumber 		string `json:"packagenumber" bson:"packagenumber"`
		ShipUser 					string `json:"shipuser" bson:"shipuser"`
		City 							string `json:"city" bson:"city"`
		District 					string `json:"district" bson:"district"`
		Address 					string `json:"address" bson:"address"`
		LargeNumber 			string `json:"largenumber" bson:"largenumber"`
		Sku 							string `json:"sku" bson:"sku"`
		CargoName 				string `json:"cargoname" bson:"cargoname"`
		Size 							string `json:"size" bson:"size"`
		Color 						string `json:"color" bson:"color"`
		Count 						string `json:"count" bson:"count"`
		Price 						float64 `json:"price" bson:"price"`
		Amount 						float64 `json:"amount" bson:"amount"`
		Cost 							float64 `json:"cost" bson:"cost"`
	}

	QueryParams struct {
		Partnerid 			string `json:"partnerid" bson:"partnerid"`
		Token 					string `json:"token" bson:"token"`
		Patrnerkey 			string `json:"patrnerkey" bson:"patrnerkey"`
		Ts 							int64 `json:"ts" bson:"ts"`
		Method 					string `json:"method" bson:"method"`
		Sign 						string `json:"sign" bson:"sign"`
	}

	QueryBody struct {
		SkuIds						string `json:"sku_ids" bson:"sku_ids"`
		Shop_id 					int `json:"shop_id" bson:"shop_id"`
		Modified_begin 		string `json:"modified_begin" bson:"modified_begin"`
		Modified_end 			string `json:"modified_end" bson:"modified_end"`
		Page_index 				int `json:"page_index" bson:"page_index"`
		Page_size 				int `json:"page_size" bson:"page_size"`
	}
	CombineBody struct{
		PageSize 			int 		`json:"page_size" bson:"page_size"`
		PageIndex 		int 		`json:"page_index" bson:"page_index"`
		DataCount 		int 		`json:"data_count" bson:"data_count"`
		PageCount 		int 		`json:"page_count" bson:"page_count"`
		HasNext 			bool		`json:"has_next" bson:"has_next"`
		Datas 				[]CombineData	`json:"datas" bson:"datas"`
		Code  				int			`json:"code" bson:"code"`
		Issuccess 		bool		`json:"issuccess" bson:"issuccess"`
		Msg 					string	`json:"msg" bson:"msg"`
	}
	CombineData struct{
		Items 						[]CombineItem `json:"items" bson:"items"`
		Iid 							string	`json:"i_id" bson:"i_id"`
		Name 							string	`json:"name" bson:"name"`
		ShortName 				string	`json:"short_name" bson:"short_name"`
		VcName 						string	`json:"vc_name" bson:"vc_name"`
		Pic 							string	`json:"pic" bson:"pic"`
		PropertiesValue 	string	`json:"properties_value" bson:"properties_value"`
		SalePrice 				float64	`json:"sale_price" bson:"sale_price"`
		Weight 						float64	`json:"weight" bson:"weight"`
		SkuId 						string	`json:"sku_id" bson:"sku_id"`
	}
	CombineItem struct{
		SrcSkuId 			string	`json:"src_sku_id" bson:"src_sku_id"`
		Qty			 			int 		`json:"qty" bson:"qty"`
		SalePrice 		float64 `json:"sale_price" bson:"sale_price"`
	}
	Body struct{
		PageSize 			int 		`json:"page_size" bson:"page_size"`
		DataCount 		int 		`json:"data_count" bson:"data_count"`
		PageIndex 		int 		`json:"page_index" bson:"page_index"`
		HasNext 			bool		`json:"has_next" bson:"has_next"`
		PageCount 		int 		`json:"page_count" bson:"page_count"`
		Orders 				[]Order	`json:"orders" bson:"orders"`
		Code  				int			`json:"code" bson:"code"`
		Issuccess 		bool		`json:"issuccess" bson:"issuccess"`
		Msg 					string	`json:"msg" bson:"msg"`
	}
	Order struct{
		Oid 							int `json:"o_id" bson:"o_id"`
		ShopId 						int`json:"shop_id" bson:"shop_id"`
		SoId 							string`json:"so_id" bson:"so_id"`
		OrderDate 				string`json:"order_date" bson:"order_date"`
		ShopStatus 				string`json:"shop_status" bson:"shop_status"`
		QuestionType 			string`json:"question_type" bson:"question_type"`
		QuestionDesc 			string`json:"question_desc" bson:"question_desc"`
		Status 						string`json:"status" bson:"status"`
		ShopBuyerId 			string`json:"shop_buyer_id" bson:"shop_buyer_id"`
		Receiverstate 		string`json:"receiver_state" bson:"receiver_state"`
		ReceiverCity 			string`json:"receiver_city" bson:"receiver_city"`
		ReceiverDistrict 	string`json:"receiver_district" bson:"receiver_district"`
		ReceiverAddress 	string`json:"receiver_address" bson:"receiver_address"`
		ReceiverName 			string`json:"receiver_name" bson:"receiver_name"`
		ReceiverMobile 		string`json:"receiver_mobile" bson:"receiver_mobile"`
		SendDate 					string`json:"send_date" bson:"send_date"`
		PayAmount 				float64`json:"pay_amount" bson:"pay_amount"`
		Freight 					float64`json:"freight" bson:"freight"`
		BuyerMessage 			string`json:"buyer_message" bson:"buyer_message"`
		Remark 						string`json:"remark" bson:"remark"`
		IsCod 						bool`json:"is_cod" bson:"is_cod"`
		Items 						[]Item`json:"items" bson:"items"`
		Type							string`json:"type" bson:"type"`
		PaidAmount				float64`json:"paid_amount" bson:"paid_amount"`
		PayDate						string`json:"pay_date" bson:"pay_date"`
		OuterPayId				string`json:"outer_pay_id" bson:"outer_pay_id"`
		Modified					string`json:"modified" bson:"modified"`
		OrderFrom					string`json:"order_from" bson:"order_from"`
		ShopName					string`json:"shop_name" bson:"shop_name"`
		Lid								string`json:"l_id" bson:"l_id"`
		WmsCoId						int `json:"wms_co_id" bson:"wms_co_id"`
		LogisticsCompany	string`json:"logistics_company" bson:"logistics_company"`
		FreeAmount				string `json:"free_amount" bson:"free_amount"`
		CoId							int `json:"co_id" bson:"co_id"`
		DrpCoName					string`json:"drp_co_name" bson:"drp_co_name"`
		Labels						string`json:"labels" bson:"labels"`
		Currency					string`json:"currency" bson:"currency"`
	}
	Item struct{
		SkuId 						string`json:"sku_id" bson:"sku_id"`
		ShopSkuId 				string`json:"shop_sku_id" bson:"shop_sku_id"`
		PropertiesValue 	string`json:"properties_value" bson:"properties_value"`
		Amount 						float64`json:"amount" bson:"amount"`
		BasePrice 				float64`json:"base_price" bson:"base_price"`
		Qty 							int`json:"qty" bson:"qty"`
		Name 							string`json:"name" bson:"name"`
		Price 						float64`json:"price" bson:"price"`
		OuterOiId 				string`json:"outer_oi_id" bson:"outer_oi_id"`
		IsGift 						bool`json:"is_gift" bson:"is_gift"`
		RefundStatus 			string`json:"refund_status" bson:"refund_status"`
		RefundId 					string`json:"refund_id" bson:"refund_id"`
		ItemStatus 				string`json:"item_status" bson:"item_status"`
		Iid 							string`json:"i_id" bson:"i_id"`
		RawSoId 					string`json:"raw_so_id" bson:"raw_so_id"`
		IsPresale 				string`json:"is_presale" bson:"is_presale"`
		OiId 							int`json:"oi_id" bson:"oi_id"`
	}
	SkuColor struct {
		ID           bson.ObjectId `json:"_id" bson:"_id"`
		SkuColorDesc string        `json:"skucolordesc" bson:"skucolordesc"`
		SkuColorCode string        `json:"skucolorcode" bson:"skucolorcode"`
	}
	SkuSize struct {
		ID          bson.ObjectId `json:"_id" bson:"_id"`
		SkuSizeDesc string        `json:"skusizedesc" bson:"skusizedesc"`
		SkuSizeCode string        `json:"skusizecode" bson:"skusizecode"`
	}
 )

var getIndex =1;
var colorMap map[string]string
var sizeMap map[string]string

func httpGet() {
	var prodsys =  &QueryParams{}
	/* 使用 make 函数 */
	prodsys.Partnerid = "ed651c5127bd53c04cb7f7dd0329f61b"
	prodsys.Token = "0ee8ec5f6a0f0378fdfa96362e57988e"
	prodsys.Patrnerkey= "a08a9c69406f57b802c027f3fc4d083c"
	prodsys.Ts = time.Now().Unix() 
	prodsys.Method = "orders.single.query"
	prodsys.Sign = ""
	ts := strconv.FormatInt(prodsys.Ts,10)
	str := prodsys.Method + prodsys.Partnerid + "token" + prodsys.Token + "patrnerkey" + prodsys.Patrnerkey + "ts" +  ts  + prodsys.Patrnerkey
	t := time.Now()
	h := md5.New()
	h.Write([]byte(str))
	prodsys.Sign = hex.EncodeToString(h.Sum(nil))
	query := "partnerid=" + prodsys.Partnerid + "&token=" + prodsys.Token + "&patrnerkey=" + prodsys.Patrnerkey + "&ts=" +  ts +"&method=" + prodsys.Method+"&sign="+prodsys.Sign
	values := url.Values{}
	values.Add("partnerid", prodsys.Partnerid)
	values.Add("token", prodsys.Token)
	values.Add("patrnerkey", prodsys.Patrnerkey)
	values.Add("ts", ts)
	values.Add("method", prodsys.Method)
	values.Add("sign", prodsys.Sign)
	timeIndex := int64(7 * 24 * 60 * 60);
	t1 := time.Unix((prodsys.Ts - timeIndex), 0)
	timeStart := t1.Format("2006-01-02 15:04:05")
	timeEnd := t.Format("2006-01-02 15:04:05")
	log.Info("timeStart",timeStart)
	log.Info("timeEnd",timeEnd)
	s := &QueryBody{Shop_id: 10214926, Modified_begin: timeStart, Modified_end: timeEnd, Page_index: getIndex, Page_size: 50}
	jsons,_:=json.Marshal(s)
	result :=string(jsons)
	jsoninfo :=strings.NewReader(result)	
	resp, err := http.Post("http://open.erp321.com/api/open/query.aspx?"+query, 
				"application/json", jsoninfo)
    if err != nil {
		log.Error("请求出错", err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	beforebodymap := Body{}
	err = json.Unmarshal(body,&beforebodymap)
	if err != nil {
		log.Error(err)
	}
	if (beforebodymap.Code == 0 && beforebodymap.Orders!= nil){
		getIndex++;
		analyseInsertData(beforebodymap);
		if (beforebodymap.HasNext == true) {
			httpGet();
		} 
	}else{
		httpGet();
	}
}

func analyseInsertData(data Body){
	var saleslist []interface{}
	// var combinelist []interface{}
	model.DB().Dbname="OxyCms"
	model.DB().Document="sales_data"
	for _,order := range data.Orders{
		if(order.Status != "Question" && order.Lid != ""){
			for _,item := range order.Items{
				obj:= insertsalesdata{}
				obj.Address = order.ReceiverAddress
				obj.CargoName = item.Name
				obj.City = order.ReceiverCity
				obj.District = order.ReceiverDistrict
				obj.LargeNumber = item.Iid
				obj.OnlineOrderNumber = order.SoId
				obj.OrderNumber = strconv.Itoa(order.Oid)
				obj.PackageNumber = order.Lid
				obj.Amount = item.Amount
				obj.Price = item.Price
				obj.Cost = item.BasePrice
				obj.Count = strconv.Itoa(item.Qty)
				obj.PayDate = until.ParseTime(order.PayDate) * 1000
				obj.ShipDate = until.ParseTime(order.SendDate) * 1000
				obj.ShipUser = order.ReceiverName
				// obj.Sku = item.SkuId
				if (item.SkuId != "" && len(item.SkuId) == 14){
					obj.Sku = item.SkuId[0 : len(item.SkuId)-1]
					obj.Color = getSkuValue(item.SkuId[0 : len(item.SkuId)-1], "color");
					obj.Size = getSkuValue(item.SkuId[0 : len(item.SkuId)-1], "size");
				} else if (item.SkuId != "" && len(item.SkuId) > 14) {
						combineErpOrder(item.SkuId, obj);
						// obj.Sku = item.SkuId
						// combinelist = append(combinelist,obj)
						continue;
				} else if (item.SkuId != "" && len(item.SkuId) > 8 && len(item.SkuId) < 12) {
						combineErpOrder(item.SkuId, obj);
						// obj.Sku = item.SkuId;
						// combinelist = append(combinelist,obj)
						continue;
				} else if (item.SkuId != "" && len(item.SkuId) < 8) {
						continue;
				} else {
						obj.Color = getSkuValue(item.SkuId, "color")
						obj.Size = getSkuValue(item.SkuId, "size")
						obj.Sku = item.SkuId
				}
				saleslist = append(saleslist,obj)
			}
		}
	}
	for _,item := range saleslist{
		err :=model.DB().Insert(item)
		if err != nil {
			log.Error("插入数据失败",err)
		}
	}
	// err :=model.DB().InsertAll(saleslist...)
	// if err != nil {
	// 	log.Error("更新失败",err)
	// }
	// saveCombineSalesData(combinelist)
}

func saveCombineSalesData (date []interface{}) {
	model.DB().Dbname="OxyCms"
	model.DB().Document="combine_data"
	err :=model.DB().InsertAll(date...)
	if err != nil {
		log.Error("插入失败",err)
	}
}

func combineErpOrder (sku string, data insertsalesdata) {
	var prodsys =  &QueryParams{}
	/* 使用 make 函数 */
	prodsys.Partnerid = "ed651c5127bd53c04cb7f7dd0329f61b"
	prodsys.Token = "0ee8ec5f6a0f0378fdfa96362e57988e"
	prodsys.Patrnerkey= "a08a9c69406f57b802c027f3fc4d083c"
	prodsys.Ts = time.Now().Unix() 
	prodsys.Method = "combine.sku.query"
	prodsys.Sign = ""
	ts := strconv.FormatInt(prodsys.Ts,10)
	str := prodsys.Method + prodsys.Partnerid + "token" + prodsys.Token + "patrnerkey" + prodsys.Patrnerkey + "ts" +  ts  + prodsys.Patrnerkey
	h := md5.New()
	h.Write([]byte(str))
	prodsys.Sign = hex.EncodeToString(h.Sum(nil))
	query := "partnerid=" + prodsys.Partnerid + "&token=" + prodsys.Token + "&patrnerkey=" + prodsys.Patrnerkey + "&ts=" +  ts +"&method=" + prodsys.Method+"&sign="+prodsys.Sign
	values := url.Values{}
	values.Add("partnerid", prodsys.Partnerid)
	values.Add("token", prodsys.Token)
	values.Add("patrnerkey", prodsys.Patrnerkey)
	values.Add("ts", ts)
	values.Add("method", prodsys.Method)
	values.Add("sign", prodsys.Sign)
	s := &QueryBody{SkuIds: sku, Page_index: 1, Page_size: 30}
	jsons,_:=json.Marshal(s)
	result :=string(jsons)
	jsoninfo :=strings.NewReader(result)	
	resp, err := http.Post("http://open.erp321.com/api/open/query.aspx?"+query, 
				"application/json", jsoninfo)
    if err != nil {
		log.Error("请求出错", err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	beforebodymap := CombineBody{}
	err = json.Unmarshal(body,&beforebodymap)
	if err != nil {
		log.Error(err)
	}
	// log.Info("resp",string(body))
	if (beforebodymap.Code == 0 && beforebodymap.Datas!= nil){
			analyseCombineData(beforebodymap.Datas, data);
	}else{
		combineErpOrder (sku, data)
	}
}
func analyseCombineData (Data []CombineData, allData insertsalesdata) {
	var saleslist []interface{}
	model.DB().Dbname="OxyCms"
	model.DB().Document="sales_data"
	for _,body := range Data{
		for _,item := range body.Items{
				obj:= insertsalesdata{}
				obj.Address = allData.Address
				obj.CargoName = allData.CargoName
				obj.City = allData.City
				obj.District = allData.District
				obj.LargeNumber = allData.LargeNumber
				obj.OnlineOrderNumber = allData.OnlineOrderNumber
				obj.OrderNumber = allData.OrderNumber
				obj.PackageNumber = allData.PackageNumber
				obj.Amount = allData.Amount
				obj.Price = allData.Price
				obj.Cost = allData.Cost
				obj.Count = strconv.Itoa(item.Qty)
				obj.PayDate = allData.PayDate
				obj.ShipDate = allData.ShipDate
				obj.ShipUser = allData.ShipUser
				obj.Color = getSkuValue(item.SrcSkuId, "color")
				obj.Size = getSkuValue(item.SrcSkuId, "size")
				obj.Sku = item.SrcSkuId
				saleslist = append(saleslist,obj)
		}
	}
	for _,item := range saleslist{
		err :=model.DB().Insert(item)
		if err != nil {
			log.Error("插入组合装数据失败",err)
		}
	}
	// err :=model.DB().InsertAll(saleslist...)
	// if err != nil {
	// 	log.Error("更新失败",err)
	// }
}

func getColor() error {
	model.DB().Dbname = "OxyDic"
	model.DB().Document = "sku_color"
	query, _, err := model.DB().Query(bson.M{}, 0, 0)
	if err != nil {
		log.Error("查询出错", err)
		return err
	}
	colorList := []SkuColor{}
	query.All(&colorList)
	var Map map[string]string
	Map = make(map[string]string)
	for _, item := range colorList {
		Map[item.SkuColorCode] = item.SkuColorDesc
	}
	colorMap = Map
	return nil
}

func getSize() error {
	model.DB().Dbname = "OxyDic"
	model.DB().Document = "sku_size"
	query, _, err := model.DB().Query(nil, 0, 0)
	if err != nil {
		log.Error("查询出错", err)
		return err
	}
	sizeList := []SkuSize{}
	query.All(&sizeList)
	var Map map[string]string
	Map = make(map[string]string)
	for _, item := range sizeList {
		Map[item.SkuSizeCode] = item.SkuSizeDesc
	}
	sizeMap = Map
	return nil
}

func getSkuValue(sku string, t string) string {
	switch t {
	case "color":
		str := sku[len(sku)-4 : len(sku)-1]
		if getLength(str) == 2 {
			if len(sku) == 12 {
				return colorMap[sku[len(sku)-3:len(sku)-1]]
			} else {
				return colorMap[sku[len(sku)-4:len(sku)-2]]

			}
		} else {
			return colorMap[sku[len(sku)-4:len(sku)-1]]
		}
		break
	case "size":
		str := sku[len(sku)-4 : len(sku)-1]
		if getLength(str) == 2 && len(sku) == 13 {
			return strings.Replace(sizeMap[sku[len(sku)-2:len(sku)-1]], "_", "", -1)
		} else {
			return strings.Replace(sizeMap[sku[len(sku)-1:len(sku)]], "_", "", -1)
		}
		break
	}
	return ""
}

func getLength(str string) int {
	var rCharacter = regexp.MustCompile("[a-zA-Z]")
	character := len(rCharacter.FindAllStringSubmatch(str, -1))
	return character
}

func main() {
	err := getColor()
	err = getSize()
	if err != nil {
		log.Error("查询出错", err)
		return
	}
	httpGet();
}
 